package com.whately.core.base.fileupload.qiniu.util;

import com.google.common.collect.Lists;
import com.whately.core.base.fileupload.qiniu.constants.QiNiuZonePrivateBucketEnum;
import com.whately.core.base.fileupload.qiniu.conf.QiNiuFileServerInfo;
import com.whately.core.base.fileupload.qiniu.model.QiNiuStorageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class UploadFileAbsolutePathUtil {

    private static QiNiuFileServerInfo qiNiuFileServerInfo;

    @Autowired
    public UploadFileAbsolutePathUtil(QiNiuFileServerInfo fsi){
        log.info("UploadFileAbsolutePathUtil init ,FileServerInfo {} ",  fsi);
        qiNiuFileServerInfo =fsi;
    }

    //获取图片的绝对路径
    public static String singleGetAbsoluteUrlWithWidthAndHeight(String relativePathAndNameWithBucket){
        if (StringUtils.isBlank(relativePathAndNameWithBucket)) {
            return StringUtils.EMPTY;
        }

        // 兼容旧版本绝对URL地址
        if (relativePathAndNameWithBucket.trim().toLowerCase().startsWith("http://")||relativePathAndNameWithBucket.trim().toLowerCase().startsWith("https://")) {
            return relativePathAndNameWithBucket;
        }
        String bucket = relativePathAndNameWithBucket.substring(0,relativePathAndNameWithBucket.indexOf("/"));

        if(StringUtils.isBlank(bucket)||relativePathAndNameWithBucket.indexOf(bucket)!=0){
            log.error("getAbsoluteUrlWithWidthAndHeight error not correct data,relativePathWithBucket {},bucket {}",relativePathAndNameWithBucket,bucket);
            return StringUtils.EMPTY;
        }

        String domain = qiNiuFileServerInfo.qiNiuImageAbsoluteUrlDomain(relativePathAndNameWithBucket,bucket);
        String path = domain + relativePathAndNameWithBucket;

        //cert 加密的图片，不允许随意访问
        if(QiNiuZonePrivateBucketEnum.BUCKET_CORP_CERT.getBucketCode().equals(bucket) || QiNiuZonePrivateBucketEnum.PRIVATE_IMG.getBucketCode().equals(bucket) ){
            path = QiNiuStorageUtil.signPrivateUrl(path);
        }
        return path;
    }


    //批量获取图片的绝对路径
    public static String[] batchGetAbsoluteUrlWithWidthAndHeight(String urls){
        List<String> ls = Lists.newArrayList();
        if(StringUtils.isNotBlank(urls)){
            String[] relativePathAndNameWithBucketArray = StringUtils.split(urls,",");
            for(String str:relativePathAndNameWithBucketArray){
                String path = singleGetAbsoluteUrlWithWidthAndHeight(str);
                if(StringUtils.isNotBlank(path)){
                    ls.add(path);
                }
            }
        }
        String[] array =new String[ls.size()];
        return ls.toArray(array);
    }
}
